package com.client.controller;

import com.alibaba.fastjson.JSONObject;
import com.client.sm9.gm.sm9.SM9Utils;
import com.client.yushi.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController("/api")
public class APIController {
    @Autowired
    Util util;

    //查询某人员是否有该权限
    @PostMapping("/isauthorized")
    public Map<String, String> isauthorized(@RequestBody JSONObject data) {
        String id = data.getString("id");   //访问者标识
        String url = data.getString("url"); //要访问的URL
        Map<String, String> map = new HashMap<>();
        map.put("result", String.valueOf(util.isAuthorised(id, url)));
        return map;
    }

    //使用某人员的密钥对消息进行AES加密
    @PostMapping("/aesencrypt")
    public byte[] encrypt(@RequestBody JSONObject data) {
        String id = data.getString("id");   //个人标识
        byte[] msg = data.getBytes("msg"); //待加密的消息
        return util.encrypt(id, msg);
    }

    //使用某人员的密钥对消息进行AES解密
    @PostMapping("/aesdecode")
    public byte[] decode(@RequestBody JSONObject data) {
        String id = data.getString("id");   //个人标识
        byte[] msg = data.getBytes("msg"); //待加密的消息
        return util.decode(id, msg);
    }

    //获取与某人通信的密钥
    @PostMapping("/getKey")
    public Map<String, String> getKey(@RequestBody JSONObject data) {
        String id = data.getString("id");   //个人标识
        byte[] key = util.getKey(id);
        Map<String, String> map = new HashMap<>();
        if (key == null)
            map.put("result", null);
        else
            map.put("result", SM9Utils.toHexPureString(key));
        return map;
    }
}
